﻿using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Input;
using WPFTemplateLib.WpfHelpers;

namespace WPFPractice.Utils
{
    /// <summary>
    /// 绑定属性基类;
    /// </summary>
    public abstract class MyBindableBase : BindableBase
    {
        public MyBindableBase()
        {
            SetCommandMethod();
        }

        #region 命令

        /// <summary>
        /// 清空消息命令
        /// </summary>
        public ICommand ClearInfoCommand { get; set; }

        #endregion

        /// <summary>
        /// 命令方法赋值(在构造函数中调用)
        /// </summary>
        private void SetCommandMethod()
        {
            ClearInfoCommand ??= new RelayCommand(o => true, o =>
            {
                if (IsResetNo)
                {
                    InfoNo = 1;
                }

                Info = "";
            });
        }

        #region 绑定

        /// <summary>
        /// 信息窗内容;
        /// </summary>
        public string Info { get; set; } = string.Empty;

        /// <summary>
        /// 信息过多是否自动删除（减半）;
        /// </summary>
        public bool IsAutoHalve { get; set; } = false;

        /// <summary>
        /// 触发信息自动减半的阈值;
        /// </summary>
        public int AutoHalveThresholdValue { get; set; } = 50000;

        /// <summary>
        /// 清空时是否重置序号
        /// </summary>
        public bool IsResetNo { get; set; } = true;

        #endregion

        #region 成员

        private long _infoNo = 1;
        /// <summary>
        /// 信息序号
        /// </summary>
        private long InfoNo
        {
            get
            {
                if (_infoNo > long.MaxValue - 10)
                {
                    _infoNo = 0;
                }

                return _infoNo++;
            }

            set => _infoNo = value;
        }

        #endregion

        #region 辅助方法

        public void ShowInfo(string info)
        {
            if (Info.Length > AutoHalveThresholdValue && IsAutoHalve)
            {
                Info = "(已删除一半信息)\r\n" + Info.Remove(0, AutoHalveThresholdValue / 2);
            }

            Info += $"[{InfoNo}][{DateTime.Now:HH:mm:ss.ffff}] {info}\r\n\r\n";
        }

        #endregion
    }
}
